
// @ts-ignore
import { userStore } from "./user"
import io, { type Socket } from "../utils/uni-socket.io.js";
import { socket_url } from "./config"
import {  getSendId, showToast } from "../utils";
import EventManager from "../Runtime/EventManager";
import DataManager from "../Runtime/DataManager";
import { Label, math } from "cc";
import { SocketSend } from "../types/type";
import { GAME_MODE_ENUM, SOCKET_TYPE } from "../../Enums";
export const useSocket = () => {
	// 连接
	function connect() {
		if (!userStore().token) {
			return false;
		}
		if (DataManager.Instance.client) {
			disconnect();
		}
		if (!DataManager.Instance.client) {
			DataManager.Instance.client = io(`${socket_url}/socket`, {
				transports: ["websocket", "polling"],
				auth: {
					isAdmin: false,
					token: userStore().token,
				},
			});
			DataManager.Instance.client.on("connect", () => {
				console.log("连接成功");
			});

			DataManager.Instance.client.on("disconnect", () => {
				console.log("关闭连接");
			});

			DataManager.Instance.client.on("msg", (data) => {
				if (data.type == 'ping') {
					DataManager.Instance.ping_time = new Date().getTime() - Number(DataManager.Instance.start_time)
					clearTimeout(DataManager.Instance.timeout)
					setPingLabel()
				}
				if(!userStore()?.info?.id) return
				EventManager.Instance.emit("msg", data)
			});

			DataManager.Instance.client.on("error", (data) => {
				showToast(data.TokenExpire)
				if(data.name.includes('TokenExpire')){
					userStore().refreshToken().then(res=>{
						console.log("刷新token后重新连接socket")
						connect()
					})
				}
				console.log(data, "sys")
			});
		}
	}

	// 断开连接
	function disconnect() {
		DataManager.Instance.client?.disconnect();
		DataManager.Instance.client = undefined;
	}

	// 发送消息
	function send(userId, content: SocketSend) {
		if (DataManager.Instance.client) {
			if (content.type == SOCKET_TYPE.PING) {
				clearTimeout(DataManager.Instance.timeout)
				DataManager.Instance.timeout = setTimeout(() => {
					DataManager.Instance.ping_time = 460
					setPingLabel()
				}, 460)
			}
			DataManager.Instance.client.emit("send", {
				toId: userId,
				content,
			});
		} else {
			showToast("[cs] client error")
			console.log("[cs] client error");
		}
	}

	return {
		connect,
		send,
		disconnect
	};
};
function setPingLabel() {
	let label = DataManager.Instance.delayedNumber.getComponent(Label)
	label.string = DataManager.Instance.ping_time + 'ms'
	if (DataManager.Instance.ping_time >= 200) {
		label.color = new math.Color("#F56C6C")
	} else {
		label.color = new math.Color("#fbfbfd")
	}
}
export function sendSocket(type: SOCKET_TYPE, content) {
	if (DataManager.Instance.gameMode != GAME_MODE_ENUM.ONLINE) return
	if(getSendId()=='') return
	useSocket().send(getSendId(), {
		type,
		roomId: DataManager.Instance.room?.id,
		owner: DataManager.Instance.room?.ownerId==userStore()?.info.id,
		roomNumber: DataManager.Instance.room?.roomNumber,
		content
	})
}
